package com.jeecms.wicool.action.user;

import static com.jeecms.common.page.SimplePage.cpn;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.entity.main.CmsGroup;
import com.jeecms.cms.manager.main.CmsGroupMng;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.user.UserAccount;
import com.jeecms.wicool.entity.user.UserInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.user.UserAccountMng;
import com.jeecms.wicool.manager.user.UserInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.weixin.WeiXinUserBean;
import com.jeecms.wicool.weixin.WeiXinUtil;

/**
 * 会员卡Action
 */
@Controller
public class UserAccountAct {
	private static final Logger log = LoggerFactory.getLogger(UserAccountAct.class);

	@SuppressWarnings("unchecked")
	@RequestMapping("/user/v_listUserAccount.do")
	public String list(Integer shopId,String userName,String vipCarNo,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(shopId,userName,vipCarNo,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		
		List<UserAccount> list = (List<UserAccount>) pagination.getList();
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		for (UserAccount userAccount : list) {
			if(userAccount.getVipLevel() != null){
				for (CmsGroup vipLevel : listVipLevel) {
					if(vipLevel.getPriority().intValue() == userAccount.getVipLevel().intValue()){
						userAccount.setVipLevelName(vipLevel.getName());
						break;
					}
				}
			}
		}
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("shopList",shopList);
		model.addAttribute("shopId",shopId);
		model.addAttribute("userName",userName);
		model.addAttribute("vipCarNo",vipCarNo);
		return "user/list_userAccount";
	}
	
	@RequestMapping("/user/v_addUserAccount.do")
	public String add(ModelMap model,HttpServletRequest request) {
		
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		List<UserInfo> userList = userMng.getAll(CmsUtils.getUser(request));
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("shopList",shopList);
		model.addAttribute("userList",userList);
		model.addAttribute("listVipLevel", listVipLevel);
		return "user/add_userAccount";
	}
	
	@RequestMapping("/user/v_toEditUserAccount.do")
	public String toEdit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount userAccount = manager.findById(id);
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("listVipLevel", listVipLevel);
		model.addAttribute("userAccount",userAccount);
		return "user/to_edit_userAccount";
	}
	@RequestMapping("/user/v_toViewUserAccount.do")
	public String toView(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount userAccount = manager.findById(id);
		List<Dictionary2> listVipLevel=DicMng.getList("vip_level");
		for (Dictionary2 dictionary2 : listVipLevel) {
			if(userAccount.getVipLevel() != null 
					&& dictionary2.getDicCode().intValue() == userAccount.getVipLevel().intValue()){
				userAccount.setVipLevelName(dictionary2.getDicName());
			}
		}
		model.addAttribute("userAccount",userAccount);
		return "user/to_view_userAccount";
	}
	@RequestMapping("/user/v_editUserAccount.do")
	public String edit(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount userAccount = manager.findById(id);
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		List<ShopInfo> shopList = shopInfoMng.getAll(CmsUtils.getUser(request));
		List<UserInfo> userList = userMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("userAccount",userAccount);
		model.addAttribute("shopList",shopList);
		model.addAttribute("userList",userList);
		model.addAttribute("listVipLevel", listVipLevel);
		return "user/edit_userAccount";
	}
	
	@RequestMapping("/user/v_viewUserAccount.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount userAccount = manager.findById(id);
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		if(userAccount.getVipLevel() != null){
			for (CmsGroup vipLevel : listVipLevel) {
				if(vipLevel.getPriority().intValue() == userAccount.getVipLevel().intValue()){
					userAccount.setVipLevelName(vipLevel.getName());
					break;
				}
			}
		}
		model.addAttribute("userAccount",userAccount);
		return "user/view_userAccount";
	}
	
	@RequestMapping("/user/o_saveUserAccount.do")
	public String save(UserAccount bean, Integer shopId,Integer userId, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateSave(bean, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		WeiXinUserBean userBean = new WeiXinUserBean();
		UserInfo user = userMng.findById(userId);
		userBean.setOpenid(user.getOpenId());
		userBean.setTo_groupid(bean.getVipLevel());
		if(WeiXinUtil.updateUserGroup(userBean)){
			bean = manager.save(bean,shopId,userId);
			log.info("save UserAccount id={}", bean.getId());
			cmsLogMng.operating(request, "UserAccount.log.save",  "id=" + bean.getId());
		}
		return "redirect:v_listUserAccount.do";
	}
	@RequestMapping("/user/o_updateUserAccount.do")
	public String update(UserAccount bean,Integer shopId,Integer userId,Integer pageNo,HttpServletRequest request,ModelMap model) {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount oldBean = manager.findById(bean.getId());
		if(!oldBean.getVipLevel().equals(bean.getVipLevel())){
			WeiXinUserBean userBean = new WeiXinUserBean();
			UserInfo user = userMng.findById(userId);
			userBean.setOpenid(user.getOpenId());
			userBean.setTo_groupid(bean.getVipLevel());
			if(WeiXinUtil.updateUserGroup(userBean)){
				bean=manager.update(bean,shopId,userId);
				model.addAttribute("message", "global.success");
				log.info("update UserAccount success. id={}", bean.getId());
				cmsLogMng.operating(request, "UserAccount.log.update",  "id=" + bean.getId());
			}else{
				model.addAttribute("message", "global.failed");
			}
		}else{
			bean=manager.update(bean,shopId,userId);
			model.addAttribute("message", "global.success");
			log.info("update UserAccount success. id={}", bean.getId());
			cmsLogMng.operating(request, "UserAccount.log.update",  "id=" + bean.getId());
		}
		return edit(bean.getId(), request, model);
	}
	
	@RequestMapping("/user/o_deleteUserAccount.do")
	public String delete(Integer[] ids, Integer shopId,String userName,String vipCarNo,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		UserAccount[] beans = manager.deleteByIds(ids);
		for (UserAccount bean : beans) {
			log.info("delete UserAccount id={}", bean.getId());
			cmsLogMng.operating(request, "UserAccount.log.delete", "id="
					+ bean.getId() + ";name=" + bean.getVipCardNo());
		}
		return list(shopId, userName, vipCarNo, pageNo, request, model);
	}
	
	
	@RequestMapping("/user/v_listUserScore.do")
	public String listUserScore(String userName,String phoneNo,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage(userName,phoneNo,cpn(pageNo),CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("phoneNo",phoneNo);
		model.addAttribute("userName",userName);
		return "user/list_userScore";
	}
	
	@RequestMapping("/user/v_to_vipLevelSet.do")
	public String to_vipLevelSet(HttpServletRequest request, ModelMap model){
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("listVipLevel", listVipLevel);
		return "user/set_vip_level";
	}
	
	@RequestMapping("/user/v_vipLevelSet.do")
	public String vipLevelSet(Integer beginScore,Integer endScore,String vipLevel,HttpServletRequest request, ModelMap model){
		if(beginScore == null || endScore == null ){
			WebErrors errors = WebErrors.create(request);
			errors.addError("参数错误！");
			return errors.showErrorPage(model);
		}
		List<String> openIds = new ArrayList<String>();
		List<UserAccount> accountList = manager.getListUserAccountByScore(beginScore, endScore);
		for (UserAccount userAccount : accountList) {
			if(StringUtils.isNotBlank(userAccount.getUser().getOpenId())){
				openIds.add(userAccount.getUser().getOpenId());
			}
		}
		if(WeiXinUtil.batchUpdateUserGroup(openIds, vipLevel)){
			manager.batchUpdateVipLevel(beginScore, endScore, vipLevel);
			model.addAttribute("message", "global.success");
		}else{
			model.addAttribute("message", "批量同步微信用户组失败！");
		}
		return to_vipLevelSet(request, model);
	}
	
	@RequestMapping("/user/v_to_change_level.do")
	public String to_batchChangeLevel(String[] ids,HttpServletRequest request, ModelMap model){
		List<CmsGroup> listVipLevel = groupMng.getWeiXinList();
		model.addAttribute("listVipLevel", listVipLevel);
		model.addAttribute("ids",org.springframework.util.StringUtils.arrayToCommaDelimitedString(ids));
		return "user/change_vip_level";
	}
	
	@RequestMapping("/user/v_change_vipLevel.do")
	public String changeVipLevel(String ids,String vipLevel,HttpServletRequest request, ModelMap model){
		if(ids == null || vipLevel == null ){
			WebErrors errors = WebErrors.create(request);
			errors.addError("参数错误！");
			return errors.showErrorPage(model);
		}
		List<String> openIds = new ArrayList<String>();
		List<UserAccount> accountList = manager.getListUserAccountByIds(ids);
		for (UserAccount userAccount : accountList) {
			if(StringUtils.isNotBlank(userAccount.getUser().getOpenId())){
				openIds.add(userAccount.getUser().getOpenId());
			}
		}
		if(WeiXinUtil.batchUpdateUserGroup(openIds, vipLevel)){
			manager.batchUpdateVipLevel(ids, vipLevel);
			model.addAttribute("message", "global.success");
		}else{
			model.addAttribute("message", "批量同步微信用户组失败！");
		}
		return list(null, null, null, 1, request, model);
	}
	
	private WebErrors validateSave( UserAccount bean, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		return errors;
	}

	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		UserAccount entity = manager.findById(id);
		if (errors.ifNotExist(entity, Product.class, id)) {
			return true;
		}
		return false;
	}
	@Autowired
	private UserAccountMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private WiShopInfoMng shopInfoMng;
	@Autowired
	private UserInfoMng userMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private CmsGroupMng groupMng;
}
